# @Time : 2025-01-02 15:43
# @Author : Fioman 
# @Phone : 13149920693
"""
eap表操作,更新表,包括插入数据和删除数据
"""
from typing import List, Tuple

from app.device_state import DeviceState
from common.datetime_helper import get_now_str, get_group_number_int
from db_tool.db_config import TableName
from db_tool.db_handler import DbHandler
from eap_tool.eap_logger import debug_eap
from eap_tool.mysql_operator import MysqlOperator
from personal_tool.enum_data import LayoutMode
from personal_tool.enum_data_eap import PcSignalType, EapMsgType
from web_tool.send_to_web_handler import eap_data_update_to_web

db = DbHandler()


def pc_signal_status_insert_one(signalType: PcSignalType, signalValue: str):
    """
    插入一条数据,根据信号
    :param signalType:
    :param signalValue:
    :return:
    """
    tableName = "pc_signal_status"
    createTime = get_now_str()
    signalValue = signalValue
    data = (signalType.name, signalType.value, signalValue, createTime)
    try:
        with MysqlOperator() as sp:
            sql = ("insert into {} (SIGNALCODE,SIGNALDES,SIGNALVALUE,CREATETIME)"
                   " values (%s, %s, %s, %s)").format(tableName)
            sp.insert_data_one(sql, data)
    except Exception as e:
        errInfo = f"in pc_signal_status_insert_one() error: {e}"
        debug_eap(errInfo)
    eap_data_update_to_web(EapMsgType.PcSignalStatus)


def pc_data_craft_update(isDeleteAuto):
    """
    更新 pc_data_craft 工艺质量表的数据,数据从哪里来呢,从本地数据库中来,或者是从生产作业的作业信息里面来
    这里就是牵涉到一个数据的来源问题,是否需要重复的创建表,还是说直接将这些作业的信息放到stateListener
    里面
    :return:
    """
    try:
        tableName = "pc_data_craft"
        with MysqlOperator() as sp:
            if isDeleteAuto:
                sp.delete_data(tableName)
            insertData = get_pc_data_craft_insert_data()
            for data in insertData:
                sql = (f"insert into {tableName} (CONTAINER, ITEMCODE, ITEMDES, UOM, "
                       f"ITEMVALUE, ISOK, GROUPNUM, CREATETIME) "
                       f" values (%s, %s, %s, %s, %s, %s, %s, %s)")
                sp.insert_data_one(sql, data)
    except Exception as e:
        errInfo = f"in pc_data_craft_update() error: {e}"
        debug_eap(errInfo)


def get_pc_data_craft_insert_data() -> List[Tuple]:
    """
    获取工艺质量表的数据
    :return:
    """
    query = {
        "key": "1"
    }
    result = db.get_data_one(TableName.workingInfos, query)
    if not result.state:
        debug_eap(result.info)
        return []
    data = result.data
    cutId = str(data.get("orderUsedId"))
    pnlSetId = str(data.get("pnlSetId"))
    knifeUsed = str(data.get("knifeUsed"))
    tableUsed = str(data.get("tableUsed"))
    cutterLifeUsed = str(data.get("cutterLifeUsed"))
    cutterKnifeName = str(data.get("cutterKnifeName"))
    result = db.get_data_one(TableName.cbjZmcParams, query)
    if not result.state:
        debug_eap(result.info)
        return []
    data = result.data
    cutSpeed = str(data.get("cut_speed_work", 1000))
    dragSpeed = str(data.get("drag_speed", 500))
    workSpeed = str(data.get("fx_work_speed", 1000))
    result = db.get_data_one(TableName.cbjCutParams, query)
    if not result.state:
        debug_eap(result.info)
        return []
    data = result.data
    cutDeep = str(data.get("cutDeep", 32))
    isOkKnife = "Y" if float(knifeUsed) < 40000 else "N"
    isOkTable = "Y" if float(tableUsed) < 60 else "N"
    isOkCutSp = "Y" if float(cutSpeed) < 1200 else "N"
    isOkDragSp = "Y" if float(dragSpeed) < 650 else "N"
    isOkWorkSp = "Y" if float(workSpeed) < 1200 else "N"
    isOkCutDp = "Y" if float(cutDeep) < 50 else "N"
    groupNum = get_group_number_int()
    createTime = get_now_str()

    result = db.get_data_one(TableName.shiftRecords, query)
    if not result.state:
        debug_eap(result.info)
        return []
    data = result.data
    runTime = data.get("runTime")
    idleTime = data.get("idleTime")
    alarmTime = data.get("alarmTime")
    pmTime = data.get("pmTime")
    prodCount = data.get("prodCount")

    res = [
        (cutId, pnlSetId, "RUN_TIME", "当班运行时间", "min", runTime, "Y", groupNum, createTime),
        (cutId, pnlSetId, "WAIT_TIME", "当班待机时间", "min", idleTime, "Y", groupNum, createTime),
        (cutId, pnlSetId, "ALARM_TIME", "当班报警时间", "min", alarmTime, "Y",
         groupNum, createTime),
        (cutId, pnlSetId, "MAINTAIN_TIME", "当班保养时间", "min", pmTime, "Y",
         groupNum, createTime),
        (cutId, pnlSetId, "NUM_VALUE", "当班生产板数", "min", prodCount, "Y",
         groupNum, createTime),
        (cutId, pnlSetId, "KNIFE_LIFE", "裁切刀已使用寿命", "min", cutterLifeUsed, "Y",
         groupNum, createTime),
        (cutId, pnlSetId, "NIFE_NAME", "刀具条码", "min", cutterKnifeName, "Y",
         groupNum, createTime),
        (cutId, pnlSetId, "CIRCULAR_KNIFE_LIFE", "圆刀使用寿命", "米(m)", knifeUsed, isOkKnife,
         groupNum, createTime),
        (cutId, pnlSetId, "TABLECLOTH_TIME", "台布使用时间", "天(d)", tableUsed, isOkTable,
         groupNum, createTime),
        (cutId, pnlSetId, "CUTTING_SPEED", "切割速度", "mm/s", cutSpeed, isOkCutSp,
         groupNum, createTime),
        (cutId, pnlSetId, "TOWING_SPEED", "裁切机拖拽速度", "mm/s", dragSpeed, isOkDragSp,
         groupNum, createTime),
        (cutId, pnlSetId, "WORWING_SPEED", "裁切机工作速度", "mm/s", workSpeed, isOkWorkSp,
         groupNum, createTime),
        (cutId, pnlSetId, "DEPTH_CUT", "下刀深度", "mm", cutDeep, isOkCutDp,
         groupNum, createTime)
    ]
    return res


def get_pc_data_status_insert_data():
    """
    获取插入表pc_data_status的数据
    :return:
    """
    createTime = get_now_str()
    # 将true和false,转换为0和1,直接使用int就行,int(True) = 1, int(False) = 0
    data1 = ("CAMZMCRUNNING", "上料控制器 运行/停止",
             str(int(DeviceState.camZmcIsRun)), createTime)
    data2 = ("CBJZMCRUNNING", "裁切机控制器 运行/停止",
             str(DeviceState.cbjZmcIsRun), createTime)
    data3 = ("CUTTERZMCRUNNING", "铡刀控制器 运行/停止",
             str(DeviceState.cutterZmcIsRun), createTime)
    query = {
        "key": DeviceState.orderUsedKey
    }
    result = db.get_data_one(TableName.orders, query)
    if not result.state:
        debug_eap(result.info)
        data = {}
    else:
        data = result.data
    jointNumber = data.get("jointNumber", "2")
    firstEdge = str(data.get("topEdge", "0"))
    secondEdge = str(data.get("leftEdge", 15))
    thirdEdge = str(data.get("bottomEdge", 15))
    fourthEdge = str(data.get("fourthEdge", 15))
    orderId = data.get("orderId", "0")
    finished = data.get("finished", "0")
    layoutMode = data.get("layoutMode", LayoutMode.Vertical.value)
    data4 = ("JOINTNUMBER", "当前作业板拼接类型", jointNumber, createTime)
    data5 = ("FIRSTEDGE", "第一刀留边宽度", firstEdge, createTime)
    data6 = ("SECONDEDGE", "第二刀留边宽度", secondEdge, createTime)
    data7 = ("THIRDEDGE", "第三刀留边宽度", thirdEdge, createTime)
    data8 = ("FORTHEDGE", "第四刀留边宽度", fourthEdge, createTime)
    data9 = ("CUTID", "当前作业的物料号", orderId, createTime)
    data10 = ("FINISHNUMBER", "当前工单已生产数量", finished, createTime)
    return [data1, data2, data3, data4, data5, data6, data7, data8, data9, data10]


def pc_data_status_update(deleteDataAuto):
    """
    更新 pc_data_ status 表数据
    :param deleteDataAuto:
    :return:
    """
    tableName = "pc_data_status"
    try:
        insertData = get_pc_data_status_insert_data()
        with MysqlOperator() as sp:
            if deleteDataAuto:
                sp.delete_data(tableName)
            for data in insertData:
                sql = (f"insert into {tableName} "
                       f"(STATUSCODE,STATUSDES,STATUSVALUE,CREATETIME) "
                       f"values (%s, %s, %s, %s)")
                sp.insert_data_one(sql, data)
    except Exception as e:
        errInfo = f"in  pc_data_status_update() error: {e}"
        debug_eap(errInfo)
